package com.learn.security.component;

import cn.hutool.core.util.StrUtil;
import com.learn.security.cache.Cache;
import com.learn.security.config.JwtConfig;
import com.learn.security.constant.CacheName;
import com.learn.security.entity.UserDetail;
import com.learn.security.provider.JwtProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : Yu.Tan
 * @date : 2022/12/9 16:56
 * @desc : **
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProvider jwtProvider;
    @Autowired
    private JwtConfig jwtConfig;
    @Autowired
    private Cache caffeineCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("JWT过滤器通过校验请求头token进行自动登录...");
        // 拿到Authorization请求头内的信息
        String authToken = jwtProvider.getToken(request);
        //校验authToken是否为空，以及token前缀是否正确
        if (StrUtil.isNotEmpty(authToken) && authToken.startsWith(jwtConfig.getTokenPrefix())) {
            // 去掉token前缀(Bearer )，拿到真实token
            authToken = authToken.substring(jwtConfig.getTokenPrefix().length());
            //获取Toke中的登录账号
            String loginAccount = jwtProvider.getSubjectFromToken(authToken);
            if (StrUtil.isNotEmpty(loginAccount) && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 查询用户
                UserDetail userDetails = caffeineCache.get(CacheName.USER, loginAccount, UserDetail.class);
                // 拿到用户信息后验证用户信息与token
                if (userDetails != null && jwtProvider.validateToken(authToken, userDetails)) {
                    // 组装authentication对象，构造参数是Principal Credentials 与 Authorities
                    // 后面的拦截器里面会用到 grantedAuthorities 方法
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
                    // 将authentication信息放入到上下文对象中
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                    log.info("JWT过滤器通过校验请求头token自动登录成功, user : {}", userDetails.getUsername());
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
